#include <LPC22xx.h>
#include "PWMDriver.h"

#define PERIODTICKS 1200000

// PINS
// P0.21 - CAP FREQ OUT

bool PWMDriver::Init()
{
	// setup pins (all pins to 0, set as output)
	PINSEL0 |= 0x00008000;

 	PWMTC = 0; // reset counter
	PWMPC = 0; // reset prescale counter
	PWMPR = 0;	// prescaler: 60Mhz/1 = 60Mhz timer
   	PWMTCR = 0; // timer mode
	PWMMCR = 0x00000002; // reset TC on MR0
	PWMPCR = 0x00000400; // single edge, enable output 2
	PWMMR0 = PERIODTICKS; // PERIOD!!! (1200000/60Mhz = 20e-3 -> 50Hz)
	PWMMR2 = 0; // reset to zero
	
	// enable
	PWMTCR = 0x00000009;

	SetOutputPWM(PWM2, 1.0f); // 1ms default!

	return true;
}

void PWMDriver::SetOutputPWM(PWMOut out, float pwm)
{
	float dutycycle = pwm/20.0f * 100;
	SetOutput(out,dutycycle); 	
}

void PWMDriver::SetOutput(PWMOut out, float dutycycle)
{
	float value = dutycycle/100 * PERIODTICKS;
	
	if( out == PWM2 )
	{
		PWMMR2 = value;
		PWMLER |= 0x00000004;
	}
}
